import socket
import sys
import logging
import datetime
import time

logging.basicConfig(level=logging.INFO)

host = ''  # Symbolic name meaning all available interfaces
port = 8501  # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);

s.bind((host, port));

print("bind udp at %s:%s" % (host, port));

#file = open("data.txt");
#line = file.readline();
#print(line);
while True:
    try:
      currtime = time.time();
      data, addr = s.recvfrom(1024);
      print('Receive from %s:%s.' % addr);
      str = data.decode('utf-8')
      print('%s Data: %s' % (time.ctime(currtime), str));
      if(str[:3] == 'WRS'):
        s.sendto(b'OK\r\n', addr);
        continue
      try:
	      file = open("data.txt");
	      line = file.readline();
	      file.close();
      except FileNotFoundError as e:
        print('FileNotFoundError:', e)
        continue
	  	
      #s.sendto(b'Hello world %s' % data, addr);
      s.sendto(b'%s\r\n' % line.encode('utf-8'), addr);
    except Exception as e:
      logging.exception(e)
      continue
    

